<template>
    <div class="console-page" v-loading="loading">
        <div style="padding: 5px;height: calc(100% - 10px);">
            <el-card :body-style="{ padding: '0px' }" shadow="never" style="margin-bottom:5px;min-width: 220px"
                ref="logTitleRef">
                <template #header>
                    <div class="e-page" style="font-size: 15px;white-space: nowrap">
                        <el-row>
                            <el-col :span="12">
                                <span class="font-auto-resize" style="padding-left: 5px;">日志详情</span>
                            </el-col>
                            <el-col :span="12" style="text-align: right;">
                                <el-button link :icon="getIcon('refresh')" style="padding: 3px 5px"
                                    @click="getServiceLogDetail" />
                            </el-col>
                        </el-row>
                    </div>
                </template>
                <el-form :model="logDetailForm" class="e-page form-item" spellcheck="false" label-width="150px"
                    style="font-size: 12px" @submit.native.prevent>
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="任务名称:" prop="value" style="margin-bottom:5px!important;">
                                <span @click="intoTask" :class="jobNameClass" :style="jobNameStyle">
                                    {{ logDetailForm.jobName }}
                                </span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="任务组别:" prop="value" style="margin-bottom:5px!important;">
                                <span class="font-auto-resize">{{ logDetailForm.jobGroup }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="任务状态:" prop="value" style="margin-bottom:5px!important;">
                                <span class="font-auto-resize">{{ logDetailForm.status }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="计划时间:" prop="value" style="margin-bottom:5px!important;">
                                <span class="font-auto-resize">{{ timeFormatSeconds(logDetailForm.triggerTime) }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="执行时间:" prop="value" style="margin-bottom:5px!important;">
                                <span class="font-auto-resize">{{ logDetailForm.fireTime }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="完成时间:" prop="value" style="margin-bottom:5px!important;">
                                <span class="font-auto-resize">{{ logDetailForm.completeTime }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="执行器地址:" prop="value" style="margin-bottom:5px!important;"
                                class="no-wrap">
                                <span class="font-auto-resize">{{ logDetailForm.ip }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="执行方式:" prop="value" style="margin-bottom:5px!important;">
                                <span class="font-auto-resize">{{ logDetailForm.execType }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="运行时长:" prop="value" style="margin-bottom:5px!important;">
                                <span class="font-auto-resize">{{ showRunTime(logDetailForm) }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
            <el-card class="logDetail">
                <div style="height: 100%;">
                    <el-scrollbar style="height: 100%;width: 100%;">
                        <p v-html="logDetailForm.logInfo" class="log-detail font-auto-resize" />
                    </el-scrollbar>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { decrypt, transferSeconds, getRandomKey, timeFormatSeconds, getIcon } from "@/utils/tools"
import router from "@/router"
import { useElMessage, useRequest } from "@usehook"
import { useElementBounding } from '@vueuse/core'
import storeInstance from "@/pinia"

const logTitleRef = $ref(null)

const height = computed(() => {
    return useElementBounding(logTitleRef).height.value + "px"
})

let route = router.currentRoute.value
let loading = $ref(false)
let logDetailForm = $ref({
    jobName: "",
    scheduledFireTime: "",
    fireTime: "",
    completeTime: "",
    status: "",
    logInfo: "",
    jobGroup: "",
    ip: "",
    execType: "",
    statusCode: 0,
    jobId: 0,
    triggerTime: ""
})

const jobNameClass = computed(() => {
    return `font-auto-resize ${logDetailForm.jobId ? 'cursor-pointer' : 'cursor-default'}`
})

const jobNameStyle = computed(() => {
    return `color: ${logDetailForm.jobId ? '#409EFF' : '#303133'}; cursor: ${logDetailForm.jobId ? 'pointer' : 'text'}; textDecoration: ${logDetailForm.jobId ? 'underline' : 'none'}`
})

const intoTask = () => {
    const name = logDetailForm.jobName
    const taskType = logDetailForm.jobGroup;
    const jobId = logDetailForm.jobId;

    if (jobId) {
        const path = '/task/' + taskType + '?id=' + jobId
        storeInstance.tagMenuStore.setTitle(name)
        router.push(path)
    }
}

const getServiceLogDetail = () => {
    let params = JSON.parse(decrypt(decodeURIComponent(route.query.key.toString()), getRandomKey()))
    loading = true
    useRequest("/joblog/logDetailCat", params).then((resData) => {
        if (resData) {
            if (resData.status) {
                logDetailForm.ip = resData.data.executorAddress
                const jobType = resData.data.jobType;

                let jobGroup;
                if (!jobType) {
                    jobGroup = "";
                } else if (jobType.startsWith("GLUE")) {
                    let type = jobType.split("_")[1];
                    jobGroup = type === "GROOVY" ? "java" : type.toLowerCase()
                } else {
                    jobGroup = jobType.toLowerCase()
                }

                logDetailForm.jobGroup = jobGroup

                if (resData.data.handleCode === 200) {
                    logDetailForm.status = '成功'
                    logDetailForm.statusCode = 200
                } else if (resData.data.triggerCode === 200 && resData.data.handleCode === 0) {
                    logDetailForm.status = '执行中'
                    logDetailForm.statusCode = 100
                } else if ((resData.data.triggerCode !== 200 && resData.data.triggerCode !== 0) || (resData.data.handleCode !== 200 && resData.data.handleCode !== 0)) {
                    logDetailForm.status = '失败'
                    logDetailForm.statusCode = 500
                } else {
                    logDetailForm.status = '未知'
                }

                logDetailForm.jobId = resData.data.jobId

                logDetailForm.execType = resData.data.runType;
                let date_regex = /((19|20)[0-9]{2})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) ([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]/g;

                let logInfo = resData.data.logInfo;
                let match = logInfo.match(date_regex) || [];
                logDetailForm.completeTime = logDetailForm.statusCode === 100 ? null : match[match.length - 1];
                logDetailForm.fireTime = match[0];
                logDetailForm.triggerTime = resData.data.triggerTime

                if (logInfo) {
                    logInfo = logInfo.replace(new RegExp('\n', "gm"), '<br>');
                    //|WARN  |
                    logInfo = logInfo.replace(new RegExp('\\|ERROR \\|', "gm"), '|' + '<b style="color: red">' + 'ERROR ' + '</b>' + '|');
                    logInfo = logInfo.replace(new RegExp('\\|WARN {2}\\|', "gm"), '|' + '<b style="color: #ff9900">' + 'WARN  ' + '</b>' + '|');
                    logInfo = logInfo.replace(new RegExp('(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{1,2}:\\d{1,2}(.\\d{3} | )\\[[a-zA-Z\\-0-9]+]) ERROR', "gm"), '<b style="color: red">' + '$1 ERROR' + '</b>');
                    logInfo = logInfo.replace(new RegExp('(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{1,2}:\\d{1,2}(.\\d{3} | )\\[[a-zA-Z\\-0-9]+]) WARN', "gm"), '<b style="color: #ff9900">' + '$1 WARN' + '</b>');

                    logInfo = logInfo.replace(new RegExp(' {2}', "gm"), '&nbsp;&nbsp;');
                } else {
                    logInfo = "暂无日志信息";
                }
                logDetailForm.logInfo = logInfo;
                logDetailForm.jobName = route.query.title;
            } else {
                if (resData.responseCode === 200) useElMessage.error("日志不存在");
            }
        }
    }).finally(() => {
        loading = false
    })

}

const showRunTime = (formData) => {
    if (formData.fireTime && formData.completeTime) {
        return transferSeconds(formData.completeTime, formData.fireTime);
    } else {
        return "--"
    }
}

onMounted(() => {
    getServiceLogDetail()
})

</script>


<style scoped>
:deep(.logDetail) {
    height: calc(100% - v-bind(height) - 7px);
}

:deep(.el-card__header) {
    padding: 3px 10px;
    height: 30px;
}

:deep(.el-form-item__label) {
    text-align: left;
    line-height: calc(var(--font-size) * 1.8);
}

:deep(.el-card__body) {
    padding: 10px;
    height: calc(100% - 20px);
}

:deep(.log-detail) {
    white-space: pre;
    overflow: auto;
    width: fit-content;
}

:deep(.el-form-item__content) {
    font-size: 14px;
    line-height: 25px;
}

:deep(.el-form-item label) {
    line-height: 25px;
    font-size: 14px;
}

:deep(.el-card) {
    background: rgba(255, 255, 255, .8);
}

:deep(p) {
    margin: 0;
}
</style>
